<script setup lang="ts">
import {nextTick, onMounted, reactive, ref, watch} from "vue";
import {type FormInterface, type Permission} from "./formType";
import type {FormInstance} from "element-plus";
import {PERMISSION_LIST} from "@/api/permission";
const dialogVisible = ref(false)
const ruleFormRef = ref<FormInstance>()
const rules = {
  name: [
    {required: true, message: '请输入权限名陈', trigger: 'blur'},
    {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
  ]
}
const props = defineProps({
  api : {
    type: Object,
    required: true
  }
})
const form = reactive<FormInterface>({
  id: '',
  name: '',
  pid: '',
  slot: ''
})
const openDialog = async(row?: FormInterface) => {
  dialogVisible.value = true
  let {data} = await PERMISSION_LIST()
  optionData.value = optionDataMap(data)
  Object.assign(form, {
    id : row?.id || '',
    name : row?.name || '',
    pid : row?.pid || '',
  })
}


const submit = async () => {
  ruleFormRef.value?.validate((valid, fields) => {
    if (valid) {
      let res = form.id === '' ?  props.api.create(form) :  props.api.update(form)
      console.log(res)
    } else {
      console.log('error submit!', fields)
    }
  })

}
const optionData = ref<Permission[]>([])
const optionDataMap = (data:Permission[]) => {
  return data.map(item => {
    if (item.children) {
      item.children = optionDataMap(item.children)
    }
    return {
      ...item,
      label: item.name,
      value: item.id
    }
  })
}
defineExpose({openDialog})
</script>

<template>
  <el-dialog
      v-model="dialogVisible"
      :title="form.id === '' ? '新增' : '编辑'"
      width="30%"
  >
    <el-form :model="form" label-width="80px"  :rules="rules" ref="ruleFormRef">
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name"  />
      </el-form-item>
      <el-form-item label="上级节点" prop="address">
        <el-tree-select v-model="form.pid" :data="optionData" check-strictly :render-after-expand="false" />
      </el-form-item>
      <el-form-item label="权限标识" prop="slot">
        <el-input v-model="form.slot" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit"
        >提交</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>

</style>